import path from "path";
import { ValidatorFactory } from "../../../validator";
import { IConfig } from "../../interface";

function validateLength(filePath: string) {
    if (filePath.length === 0) {
        return { data: filePath, success: false };
    }
    return { data: filePath, success: true };
}

function validateFilePath(filePath: string, config: IConfig) {
    const rootPath = config.rootPath;
    const resolvedPath = path.resolve(filePath);
    const relativePath = path.relative(rootPath, resolvedPath);
    const parsedPath = path.parse(resolvedPath);

    // 检查路径是否在允许的根目录内
    if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
        return {
            data: filePath,
            success: false,
            message: `Path ${filePath} is not within the allowed root directory: ${rootPath}`
        };
    }

    // 检查文件名是否包含非法字符
    const invalidChars = ["/", "\\", "?", "%", "*", ":", "|", '"', "<", ">", "."];
    for (const char of invalidChars) {
        if (parsedPath.base.includes(char)) {
            // 使用 parsedPath.base 来检查文件名
            return {
                data: filePath,
                success: false,
                message: `Invalid character in file name: ${char}`
            };
        }
    }

    // 检查文件名是否以空格或点开头或结尾
    if (
        parsedPath.base.startsWith(" ") ||
        parsedPath.base.endsWith(" ") ||
        parsedPath.base.startsWith(".") ||
        parsedPath.base.endsWith(".")
    ) {
        return {
            data: filePath,
            success: false,
            message: "File name cannot start or end with space or dot"
        };
    }

    return { data: filePath, success: true };
}

export const filePathValidator = new ValidatorFactory<string, [IConfig]>({
    validateLength,
    validateFilePath
}).createValidator();
